﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office;
using Microsoft.Office.Core;
using Microsoft.Office.Interop.Excel;

using System.Text.RegularExpressions;

namespace japanese
{
    public partial class mainform : Form
    {
         
        //插入
        insertForm insertform = new insertForm();
        //记录
        LogSetting setting = new LogSetting();

        //treeview
        LinkedList<TreeNode> treenodes = new LinkedList<TreeNode>();

        //excel 文件操作
        LinkedList<ExcelOperation> excels;


        //当前操作excelOperation
        ExcelOperation currentexcel;
        int indexOfSheet = 0;
        TreeNode currentNode;

        //显示引擎
        DisplayEngine engine = new DisplayEngine();

        //焦点
       


        public mainform()
        {
            InitializeComponent();

            this.setting.logSettingRecover();

            this.RefreshItem(this.setting);

            this.excels = ExcelOperation.RecoverLog();
            if (this.excels == null)
            {
                this.excels = new LinkedList<ExcelOperation>();
            }
            else { 
                //添加到treeview列表中
                foreach (ExcelOperation eo in this.excels)
                {
                    this.treeView1.Nodes.Add(eo.ToTreeNode());
                }
            }



            //treeview 的双击事件
            this.treeView1.NodeMouseDoubleClick += new TreeNodeMouseClickEventHandler(treeView1_NodeMouseDoubleClick);


            this.listBox_preview.DrawItem += new DrawItemEventHandler(listBox_preview_DrawItem);

            this.SingleLineHeight = this.listBox_preview.ItemHeight;

            //listbox select
            this.listBox_preview.SelectedIndexChanged += new EventHandler(listBox_preview_SelectedIndexChanged);

            //刷新事件
            this.engine.HanZiEvent += new TextDisplayEvent(engine_HanZiEvent);
            this.engine.JianMinEvent += new TextDisplayEvent(engine_JianMinEvent);
            this.engine.YuLiEvent += new TextDisplayEvent(engine_YuLiEvent);
            this.engine.LijuEvent += new TextDisplayEvent(engine_LijuEvent);
            this.engine.RowChange += new RowChangeEvent(engine_RowChange);


            //窗口大小改变
            this.SizeChanged += new EventHandler(mainform_SizeChanged);


           //快捷键
            this.KeyPreview = true;
            this.KeyDown += new KeyEventHandler(mainform_KeyDown);

            this.panel_hanzi.Click += new EventHandler(panel_hanzi_Click);
            this.panel_jianmin.Click += new EventHandler(panel_hanzi_Click);
            this.panel_liju.Click += new EventHandler(panel_hanzi_Click);
            this.panel_yuyi.Click += new EventHandler(panel_hanzi_Click);


            //未处理异常
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);


            Color cc = Color.FromArgb(100, this.label_tips_yuyi.BackColor.R,
                this.label_tips_yuyi.BackColor.G,
                this.label_tips_yuyi.BackColor.B);
            this.label_tips_yuyi.BackColor =
                this.label_tips_Liju.BackColor =
                this.label_tips_jiamin.BackColor =
                this.label_tips_hanzi.BackColor = cc;
            
        
        }



        void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            //throw new NotImplementedException();
            MessageBox.Show("未处理异常:"+ "from:"+ sender.ToString() + "exception:"+ e.ExceptionObject.ToString());
        }

        void panel_hanzi_Click(object sender, EventArgs e)
        {
            //throw new NotImplementedException();
            this.treeView1.Focus();
        }

        void mainform_KeyDown(object sender, KeyEventArgs e)
        {
            //throw new NotImplementedException();

            switch (e.KeyCode)
            { 
                case Keys.Left:
                case Keys.Up:
                    if (this.currentexcel == null)
                    {
                        MessageBox.Show("请选择要阅读的文件");
                    }
                    else
                    {
                        this.engine.Refresh(KeyButton.Pre);
                    }
                    break;
                case Keys.Right:
                case Keys.Down: 
                case Keys.Enter:
                    if (this.currentexcel == null)
                    {
                        MessageBox.Show("请选择要阅读的文件");
                    }
                    else
                    {
                        this.engine.Refresh(KeyButton.Next);
                    }
                    break;
            }

        }


        //窗口缩放
        void mainform_SizeChanged(object sender, EventArgs e)
        {
            //throw new NotImplementedException();
            int margin = this.panel_hanzi.Margin.Horizontal; 
            int pan = (this.tableLayoutPanel1.Height - 45) / 4 - margin;
            int range = pan + margin;
            

            this.panel_jianmin.Height =
                this.panel_liju.Height =
                this.panel_hanzi.Height =
                this.panel_yuyi.Height = pan;

            System.Drawing.Point p = new System.Drawing.Point();
            p.X = this.panel_jianmin.Location.X;
            p.Y = range + margin;
            this.panel_hanzi.Location = p; p.Y += range;
            this.panel_yuyi.Location = p; p.Y += range;
            this.panel_liju.Location = p; p.Y += range;
            this.panel_button.Location = p;
           
        }

        

        void engine_RowChange(object sender, RowChangeEventArgs args)
        {
            //throw new NotImplementedException();
            try {
                if (this.listBox_preview.InvokeRequired)
                {
                    RowChangeEvent a = new RowChangeEvent(engine_RowChange);
                    this.listBox_preview.Invoke(a, new object[] { sender, args });
                }
                else { 
                 this.listBox_preview.SelectedIndex = args.nowrow - 2;              
                }
 
            }
            catch { }
        }

        void engine_LijuEvent(object sender, TextEventArgs args)
        {
            if (this.label_liju.InvokeRequired)
            {
                TextDisplayEvent a = new TextDisplayEvent(engine_LijuEvent);
                this.label_liju.Invoke(a, new object[] { sender, args });
            }
            else
            {
                this.label_liju.Text = args.text;
            }
            
        }

        void engine_YuLiEvent(object sender, TextEventArgs args)
        {
            if (this.label_yuyi.InvokeRequired)
            {
                TextDisplayEvent a = new TextDisplayEvent(engine_YuLiEvent);
                this.label_yuyi.Invoke(a, new object[] { sender, args });
            }
            else
            {
                this.label_yuyi.Text = args.text;
            }
        }

        void engine_JianMinEvent(object sender, TextEventArgs args)
        {
            if (this.label_jianMing.InvokeRequired)
            {
                TextDisplayEvent a = new TextDisplayEvent(engine_JianMinEvent);
                this.label_jianMing.Invoke(a, new object[] { sender, args });
            }
            else
            {
                this.label_jianMing.Text = args.text;
            }
        }

        void engine_HanZiEvent(object sender, TextEventArgs args)
        {
            if (this.label_hanzi.InvokeRequired)
            {
                TextDisplayEvent a = new TextDisplayEvent(engine_HanZiEvent);
                this.label_hanzi.Invoke(a, new object[] { sender, args });
            }
            else
            {
                this.label_hanzi.Text = args.text;
            }
        }

        void listBox_preview_SelectedIndexChanged(object sender, EventArgs e)
        {
            //throw new NotImplementedException();
            this.engine.CurrentSheetRows = this.listBox_preview.SelectedIndex+2;
            this.engine.RowsMax = this.listBox_preview.Items.Count;
            this.engine.DisplayItemInit();
            this.engine.ClearDisplay();
            this.engine.Refresh(KeyButton.Refresh);
            this.engine.CurrentExcel.LogSheetItemSet(this.indexOfSheet, this.engine.CurrentSheetRows);

        }



        private Color RowBackColorAlt=Color.FromArgb(200,200,200);//交替色 
        private Color RowBackColorSel = Color.FromArgb(150, 200, 250);//选择项目颜色 
        private int SingleLineHeight = 0;
        void listBox_preview_DrawItem(object sender, DrawItemEventArgs e)
        {
            if (e.Index < 0) return;
            //listBox_preview_MeasureItem(sender, e);

            Brush myBrush = Brushes.Black; 
 
            if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) 
            { 
                myBrush = new SolidBrush(RowBackColorSel); 
            } 
            else if (e.Index % 2 == 0) 
            { 
                myBrush = new SolidBrush(RowBackColorAlt); 
            } 
            else 
            { 
                myBrush = new SolidBrush(Color.White); 
            } 
            e.Graphics.FillRectangle(myBrush, e.Bounds); 
            e.DrawFocusRectangle();//焦点框 
 
            //文本 
            StringFormat strFormat = new StringFormat();
            strFormat.Alignment = StringAlignment.Near;
            strFormat.LineAlignment = StringAlignment.Center;
            e.Graphics.DrawString(listBox_preview.Items[e.Index].ToString(), e.Font, new SolidBrush(e.ForeColor), e.Bounds, strFormat); 
    }


        void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            //throw new NotImplementedException();
            if (this.treeView1.Nodes.Count == 0)
            {
                MessageBox.Show("请先导入表格");
            }
            else
            {
                foreach (ExcelOperation op in this.excels)
                {
                    String name = ((this.treeView1.SelectedNode.Parent==null)?this.treeView1.SelectedNode.Text:this.treeView1.SelectedNode.Parent.Text);
                    
                    //文件名
                    if (op.filename == name)
                    {
                        int index = 0;

                        //sheet index
                        if (this.treeView1.SelectedNode.TreeView.SelectedNode != null)
                            index = this.treeView1.SelectedNode.TreeView.SelectedNode.Index;
                        else index = 0;

                        index += 1;

                        this.label_tips.Text = op.filename + ":" +
                            (op.workboos.Worksheets[index] as Worksheet).Name;
                        if(this.currentexcel != null)
                        if (index == this.indexOfSheet && this.currentexcel.filename == op.filename) return;

                        this.currentexcel = op;
                        this.indexOfSheet = index;
                        this.currentNode = ((this.treeView1.SelectedNode.Parent == null) ? this.treeView1.SelectedNode : this.treeView1.SelectedNode.Parent);

                        this.engine.CurrentExcel = op;
                        this.engine.CurrentSheetIndex = index;
                        this.engine.DisplayItemInit();

                        this.listBox_preview.Items.Clear();

                        //在listbox列出所有项
                        int i = 0;
                        Worksheet sheet = this.currentexcel.workboos.Worksheets[this.indexOfSheet] as Worksheet;
                        for(i = 1;i< (sheet.Columns[(int)DisplayColomnInformation.JiaMin] as Range).Rows.Count;i++)
                        {
                            //从第二行开始读取
                            String s = (sheet.Cells[i+1,(int)DisplayColomnInformation.JiaMin] as Range).Text.ToString();
                            if (s != "")
                            {
                                this.listBox_preview.Items.Add(s);
                            }
                            else break;
                        }

                        //添加提示文本
                        this.label_tips_hanzi.Text = this.currentexcel.ReadSheet(this.indexOfSheet, 1, 2);
                        this.label_tips_jiamin.Text = this.currentexcel.ReadSheet(this.indexOfSheet, 1, 3);
                        this.label_tips_Liju.Text = this.currentexcel.ReadSheet(this.indexOfSheet, 1, 5);
                        this.label_tips_yuyi.Text = this.currentexcel.ReadSheet(this.indexOfSheet, 1, 4);

                    }
                }
            }
        }


        private void RefreshItem(LogSetting s)
        {

            //显示 

            if (s == null) return;
            this.JiaMinToolStripMenuItem.Checked = false;
            this.HanZiToolStripMenuItem.Checked = false;
            this.YuYiToolStripMenuItem.Checked = false;
            switch (s.display) { 
                case LogSettingDisplay.HanZiFirst:
                    this.HanZiToolStripMenuItem.Checked = true;
                    break;
                case LogSettingDisplay.JiaMingFirst:
                    this.JiaMinToolStripMenuItem.Checked = true;
                    break;
                case LogSettingDisplay.YuYiFirst:
                    this.YuYiToolStripMenuItem.Checked = true;
                    break;
                default: break;
            }

            //模式
            this.随机背诵ToolStripMenuItem.Checked = false;
            this.随机阅读ToolStripMenuItem.Checked = false;
            this.顺序阅读ToolStripMenuItem.Checked = false;
            this.顺序背诵ToolStripMenuItem.Checked = false;
            switch (s.mode)
            { 
                case LogSettingMode.RandBrouse:
                    this.随机阅读ToolStripMenuItem.Checked = true;
                    break;
                case LogSettingMode.RandRecite:
                    this.随机背诵ToolStripMenuItem.Checked = true;
                    break;
                case LogSettingMode.SequenceBrouse:
                    this.顺序阅读ToolStripMenuItem.Checked = true;
                    break;
                case LogSettingMode.SequenceRecite:
                    this.顺序背诵ToolStripMenuItem.Checked = true;
                    break;
                default: break;

            }

            this.禁止ToolStripMenuItem.Checked = false;
            this.sToolStripMenuItem.Checked = false;
            this.sToolStripMenuItem1.Checked = false;
            this.sToolStripMenuItem2.Checked = false;
            this.sToolStripMenuItem3.Checked = false;
            this.sToolStripMenuItem4.Checked = false;

            switch (s.times)
            { 
                case LogSettingTimes.Disable:
                    this.禁止ToolStripMenuItem.Checked = true;
                    break;
                case LogSettingTimes.Second1:
                    this.sToolStripMenuItem.Checked = true;
                    break;
                case LogSettingTimes.Second2:
                    this.sToolStripMenuItem1.Checked = true;
                    break;
                case LogSettingTimes.Second3:
                    this.sToolStripMenuItem2.Checked = true;
                    break;
                case LogSettingTimes.Second4:
                    this.sToolStripMenuItem3.Checked = true;
                    break;
                case LogSettingTimes.Second5:
                    this.sToolStripMenuItem4.Checked = true;
                    break;
                default: break;

            }

            //颜色
            this.panel_hanzi.BackColor =
                this.panel_jianmin.BackColor =
                this.panel_liju.BackColor =
                this.panel_yuyi.BackColor = this.setting.ToBackGroundColor();

            //字体
            this.label_yuyi.Font =
                this.label_hanzi.Font =
                this.label_liju.Font =
                this.label_jianMing.Font = new System.Drawing.Font(this.setting.font, this.setting.fontsize);
            this.label_hanzi.ForeColor =
                this.label_jianMing.ForeColor =
                this.label_liju.ForeColor =
                this.label_yuyi.ForeColor = this.setting.ToFontColor();


            this.engine.DisplayStyle = this.setting.display;
            this.engine.DisplayMode = this.setting.mode;
            this.engine.DisplayTime = this.setting.times;

        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //保存
            this.setting.logSettingSave();

            foreach (ExcelOperation excell in this.excels) {
                excell.log.SaveLog();
            } 
           

            //退出 
            System.Windows.Forms.Application.Exit();// Application.Exit();
        }

        private void 导入陌生词ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.insertform.Show();
        }

        private void 假名ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.JiaMinToolStripMenuItem.Checked == false) {
                this.setting.display = LogSettingDisplay.JiaMingFirst;
                this.RefreshItem(this.setting);
            }
        }

        private void 汉字假名意义句子ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.HanZiToolStripMenuItem.Checked == false)
            {
                this.setting.display = LogSettingDisplay.HanZiFirst;
                this.RefreshItem(this.setting);
            }
        }

        private void 意义假名汉字句子ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.YuYiToolStripMenuItem.Checked == false)
            {
                this.setting.display = LogSettingDisplay.YuYiFirst;
                this.RefreshItem(this.setting);
            }
        }

        private void 随机阅读ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.随机阅读ToolStripMenuItem.Checked == false)
            {
                this.setting.mode = LogSettingMode.RandBrouse;
                this.RefreshItem(this.setting);
            }
        }

        private void 随机背诵toolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.随机背诵ToolStripMenuItem.Checked == false)
            {
                this.setting.mode = LogSettingMode.RandRecite;
                this.RefreshItem(this.setting);
            }
        }

        private void 顺序阅读ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.顺序阅读ToolStripMenuItem.Checked == false)
            {
                this.setting.mode = LogSettingMode.SequenceBrouse;
                this.RefreshItem(this.setting);
            }
        }

        private void 顺序背诵ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.顺序背诵ToolStripMenuItem.Checked == false)
            {
                this.setting.mode = LogSettingMode.SequenceRecite;
                this.RefreshItem(this.setting);
            }
        }

        private void 导入表格ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog d = new OpenFileDialog();
            if (d.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //导入文件
                String filename = d.SafeFileName;

                foreach (ExcelOperation oo in excels) {
                    if (oo != null) {
                        if (oo.filename == filename) {
                            MessageBox.Show("文件已经存在");
                            return;
                        }
                    }
                }

                //导入文件
                try
                {
                    ExcelOperation nexcel = new ExcelOperation(filename);
                    this.treeView1.Nodes.Add(nexcel.ToTreeNode());
                    this.excels.AddLast(nexcel);

                }
                catch (Exception ee)
                {
                    MessageBox.Show("创建文件列表失败");
                }

            }

        }


        private void button_next_Click(object sender, EventArgs e)
        {
            if (this.currentexcel == null)
            {
                MessageBox.Show("请选择要阅读的文件");
            }
            else{
                this.engine.Refresh(KeyButton.Next);
            }
        }

        private void button_above_Click(object sender, EventArgs e)
        {
            if (this.currentexcel == null)
            {
                MessageBox.Show("请选择你要阅读的文件");
            }
            else {
                this.engine.Refresh(KeyButton.Pre);
            }
        }


        private void button_pre_Click(object sender, EventArgs e)
        {  
            if (this.button_pre.Text == "<")
            {
                this.button_pre.Text = ">";
                {
                    this.splitContainer2.Panel2Collapsed = true;
                }
            }
            else {
                this.button_pre.Text = "<";
                this.splitContainer2.Panel2Collapsed = false;
            }
        }


        protected override void OnClosed(EventArgs e)
        {
                foreach(ExcelOperation aa in this.excels)
                {
                    aa.mDisplose(true);
                }
                this.setting.logSettingSave();
                base.OnClosed(e);
        }

           private void 禁止ToolStripMenuItem_Click(object sender, EventArgs e)
           {
               if (this.setting.times != LogSettingTimes.Disable) { 
                this.setting.times = LogSettingTimes.Disable;
                this.RefreshItem(this.setting);              
               }
           }

           private void sToolStripMenuItem_Click(object sender, EventArgs e)
           {
               if (this.setting.times != LogSettingTimes.Second1)
               {
                   this.setting.times = LogSettingTimes.Second1;
                   this.RefreshItem(this.setting);
               }
           }

           private void sToolStripMenuItem1_Click(object sender, EventArgs e)
           {
               if (this.setting.times != LogSettingTimes.Second2)
               {
                   this.setting.times = LogSettingTimes.Second2;
                   this.RefreshItem(this.setting);
               }
           }

           private void sToolStripMenuItem2_Click(object sender, EventArgs e)
           {
               if (this.setting.times != LogSettingTimes.Second3)
               {
                   this.setting.times = LogSettingTimes.Second3;
                   this.RefreshItem(this.setting);
               }
           }

           private void sToolStripMenuItem3_Click(object sender, EventArgs e)
           {
               if (this.setting.times != LogSettingTimes.Second4)
               {
                   this.setting.times = LogSettingTimes.Second4;
                   this.RefreshItem(this.setting);
               }
           }

           private void sToolStripMenuItem4_Click(object sender, EventArgs e)
           {
               if (this.setting.times != LogSettingTimes.Second5)
               {
                   this.setting.times = LogSettingTimes.Second5;
                   this.RefreshItem(this.setting);
               }
           }

           private void toolStripMenuItem1_Click(object sender, EventArgs e)
           {
               if (this.currentexcel != null)
               {
                   this.excels.Remove(this.currentexcel);
                   //保存
                   this.setting.logSettingSave();

                   foreach (ExcelOperation excell in this.excels)
                   {
                       excell.log.SaveLog();
                   }

                   this.currentexcel.SaveLog(true);

                   //删除tree
                   this.treeView1.Nodes.Remove(this.currentNode);

                   this.currentexcel.mDisplose(true);


                   this.currentexcel = null;

                   this.listBox_preview.Items.Clear();

               }
           }

           private void button3_Click(object sender, EventArgs e)
           {
               if (this.button3.ImageIndex == 2)
               {
                   if (this.engine != null)
                   {
                       this.engine.TimerEnable();
                       this.button3.ImageIndex = 1;
                   }
                   else {
                       MessageBox.Show("请选择文件");
                   }
               }
               else {
                   if (this.engine != null)
                   {
                       this.engine.TimerDisable();
                       this.button3.ImageIndex = 2;
                   }
               }
           }

           private void hScrollBar_fontsize_Scroll(object sender, ScrollEventArgs e)
           {
               float maxsize = 50;
               float size = this.hScrollBar_fontsize.Value * maxsize / this.hScrollBar_fontsize.Maximum;
               size += 10;
               System.Drawing.Font f = new System.Drawing.Font(this.label_hanzi.Font.FontFamily,size);

               this.label_hanzi.Font = 
                   this.label_jianMing.Font =
                   this.label_liju.Font =
                   this.label_yuyi.Font = f;

               this.setting.fontsize = f.Size;
           }

           private void 背景颜色ToolStripMenuItem_Click(object sender, EventArgs e)
           {
               ColorDialog cd = new ColorDialog();
               DialogResult cdr =  cd.ShowDialog();
               switch (cdr)
               { 
                   case System.Windows.Forms.DialogResult.OK:
                   case System.Windows.Forms.DialogResult.Yes:
                       this.panel_hanzi.BackColor = cd.Color;
                       this.panel_jianmin.BackColor = cd.Color;
                       this.panel_yuyi.BackColor = cd.Color;
                       this.panel_liju.BackColor = cd.Color;
                       this.setting.backcolor = cd.Color.ToArgb().ToString("X");
                       break;
                   
               }

           }

           private void 字体ToolStripMenuItem_Click(object sender, EventArgs e)
           {
               FontDialog fd = new FontDialog();
               DialogResult r = fd.ShowDialog();
               switch (r)
               { 
                   case System.Windows.Forms.DialogResult.OK:
                   case System.Windows.Forms.DialogResult.Yes:
                       this.label_hanzi.Font =
                           this.label_jianMing.Font =
                           this.label_liju.Font =
                           this.label_yuyi.Font = fd.Font;
                       this.setting.font = fd.Font.FontFamily.Name;
                       this.setting.fontsize = fd.Font.Size;
                       break;
               }
           }

           private void 关于ToolStripMenuItem_Click(object sender, EventArgs e)
           {
               about aa = new about();
               aa.Show();
           }

           private void toolStripMenuItem2_Click(object sender, EventArgs e)
           {
               ColorDialog cd = new ColorDialog();
               DialogResult r = cd.ShowDialog();
               switch (r)
               { 
                   case System.Windows.Forms.DialogResult.OK:
                   case System.Windows.Forms.DialogResult.Yes:
                       this.setting.fontcolor = cd.Color.ToArgb().ToString("X");
                       this.RefreshItem(this.setting);
                       break;
                   default:
                       break;
               }
           }

           private void button_treeviewHide_Click(object sender, EventArgs e)
           {
               if (this.button_treeviewHide.Text == "<")
               {
                   this.button_treeviewHide.Text = ">";
                   { this.splitContainer2.Panel1Collapsed = true; }
               }
               else
               {
                   this.button_treeviewHide.Text = "<";
                   this.splitContainer2.Panel1Collapsed = false;
               }
           }
    }
}
